<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="800px" append-to-body custom-class="import-dialog">
      <div v-loading="loading">
        <el-form ref="form" :model="form" :rules="rules" label-width="130px">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="机构LOGO" prop="icon">
                <PictureLibrary v-model="form.icon" :limit="1"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业执照" prop="businessLicense">
                <PictureLibrary v-model="form.businessLicense" :limit="1"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="机构名称" prop="tenantName">
                <el-input v-model="form.tenantName" placeholder="请输入机构名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域" prop="region">
                <el-cascader ref="areaPicker" v-model="form.region" :props="areaProps" :show-all-levels="true"
                             @change="handleChangeArea" style="width: 100%;"
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          <el-row :gutter="10">-->
          <!--            <el-col :span="12">-->
          <!--              <el-form-item label="类型" prop="typeList">-->
          <!--                <el-select v-model="form.typeList" placeholder="请选择机构类型" multiple clearable style="width: 100%;">-->
          <!--                  <el-option v-for="dict in dict.type.department_type" :key="dict.value" :label="dict.label"-->
          <!--                    :value="dict.value" />-->
          <!--                </el-select>-->
          <!--              </el-form-item>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
          <el-row :gutter="10">


          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="form.detailAddress" placeholder="请输入详细地址"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="是否存在上级机构" prop="depParentState">
                <el-radio-group v-model="form.depParentState">
                  <el-radio label="0">不存在</el-radio>
                  <el-radio label="1">存在</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.depParentState == 1">
              <el-form-item label="上级机构名称" prop="parentIdList">
                <!-- TODO -->
                <el-select v-model="form.parentIdList" placeholder="请选择" filterable multiple>
                  <el-option v-for="item in departmentList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactsName">
                <el-input v-model="form.contactsName" placeholder="请输入联系人名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contactsPhone">
                <el-input v-model="form.contactsPhone" maxlength="11" placeholder="请输入联系方式" v-input.int/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="用户最大数量" prop="maxPopulation">
                <el-input v-model="form.maxPopulation" placeholder="请输入机构名称" v-input.intLimitMin="-1"/>
                <span>设置企业用户数量，不限制可输入-1</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房屋最大数量" prop="maxHouse">
                <el-input v-model="form.maxHouse" placeholder="请输入机构名称" v-input.intLimitMin="-1"/>
                <span>设置企业新增房屋数量，不限制请输入-1</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="合同功能" prop="contractStatus">
                <el-radio-group v-model="form.contractStatus">
                  <el-radio label="0">不开通</el-radio>
                  <el-radio label="1">开通</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账单功能" prop="billStatus">
                <el-radio-group v-model="form.billStatus">
                  <el-radio label="0">不开通</el-radio>
                  <el-radio label="1">开通</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="机构状态" prop="tenantStatus">
                <el-radio-group v-model="form.tenantStatus">
                  <el-radio label="1">正常</el-radio>
                  <el-radio label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArea } from '@/api/system/config'
import { insertDepartment, updateDepartment, listDepartment } from '@/api/sys-enterprise'

export default {
  props: {
    title: {
      default: '新增机构信息'
    },
    value: {
      default: false
    },
    data: {
      default: undefined
    }
  },
  dicts: ['department_type'],
  data() {
    return {
      visible: false,
      form: {},
      rules: {
        tenantName: [
          { required: true, message: '请输入机构名称', trigger: 'blur' }
        ],
        typeList: [
          { required: true, message: '请选择机构类型', trigger: 'blur' }
        ],
        depParentState: [
          { required: true, message: '上级机构是否存在', trigger: 'blur' }
        ],
        parentIdList: [
          { required: true, message: '请选择上级机构', trigger: 'blur' }
        ],
        contactsPhone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        maxPopulation: [
          { required: true, message: '请输入用户最大数量', trigger: 'blur' }
        ],
        maxHouse: [
          { required: true, message: '请输入房屋最大数量', trigger: 'blur' }
        ],
        contractStatus: [
          { required: true, message: '请选择是否开通合同功能', trigger: 'blur' }
        ],
        billStatus: [
          { required: true, message: '请选择是否开通账单功能', trigger: 'blur' }
        ]
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
      //机构列表
      listDepartment: [],
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 2
              }))
              resolve(areas)
            }
          )
        }
      }
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init()
      }
      this.visible = newVal // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit('input', val) // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  created() {
    this.getListDepartment()
  },
  methods: {
    init() {
      this.reset()
      if (this.data.tenantId) {
        this.form = this.data
        this.form.typeList = this.form.typeList ? this.data.type.split(',') : undefined
        this.form.region = [this.data.provinceId, this.data.cityId, this.data.districtId]
      }
    },
    reset() {
      // this.dateRange = [];
      this.form = {
        tenantName: undefined,//机构名称
        provinceId: undefined,//省id
        provinceName: undefined,//省名称
        cityId: undefined,//市id
        cityName: undefined,//市名称
        districtId: undefined,//区id
        districtName: undefined,//区名称
        detailAddress: undefined,//详细地址
        icon: undefined,//logo
        businessLicense: undefined,//营业执照
        depParentState: '0',//是否存在上级机构：0不存在；1存在
        parentIdList: undefined,//上级机构id集合
        typeList: undefined,//机构类型id集合
        contactsName: undefined,//联系人
        contactsPhone: undefined,//联系电话
        maxPopulation: undefined,//企业最大人数
        maxHouse: undefined,//房屋最大数量
        contractStatus: '0',//是否开通合同功能：0否；1是(字典字段:contract_status)
        billStatus: '0',//是否开通账单功能：0否；1是(字典字段:bill_status)
        tenantStatus: '1'//是否启用：0禁用；1正常
      }
      this.resetForm('form')
    },
    //区域选择
    handleChangeArea(val) {
      const checkedNode = this.$refs['areaPicker'].panel.getNodeByValue(val)
      const ids = checkedNode.path
      const labels = checkedNode.pathLabels
      // if (labels[1] == "市辖区") {
      //   this.cityName = labels[0];
      // } else {
      //   this.cityName = labels[1];
      // }
      // this.form.provinceName = labels[0];
      // this.form.cityName = labels[1];
      // this.form.districtName = labels[2];
      // this.form.streetName = labels[3];
      // this.form.communityName = labels[4];
      //console.log(this.cityName);

      this.form.provinceId = ids[0]
      this.form.provinceName = labels[0]
      this.form.cityId = ids[1]
      this.form.cityName = labels[1]
      this.form.districtId = ids[2]
      this.form.districtName = labels[2]
    },
    //获取机构列表
    getListDepartment() {
      listDepartment().then(response => {
        this.departmentList = response.data.map(item => {
          return {
            value: item.tenantId,
            label: item.tenantName
          }
        })
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.tenantId) {
            updateDepartment(this.form).then(response => {
              if (response.code == 200) {
                this.$emit('success')
                this.$message.success(response.msg)
                this.visible = false
              } else {
                this.$message.error(response.msg)
              }
            })
          } else {
            insertDepartment(this.form).then(response => {
              if (response.code == 200) {
                this.$emit('success')
                this.$message.success(response.msg)
                this.visible = false
              } else {
                this.$message.error(response.msg)
              }
            })
          }

        }
      })
    },
    cancel() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog.scss";
</style>
